package com.study.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.study.bean.Person;
import com.study.bean.Yellow;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * Profile:
 *         Spring 为我们提供的可以根据当前环境，动态的激活和切换一系列组件的功能
 *  开发环境 、测试环境 、生产环境
 *  数据源 (/A) (/B) (/C)
 *
 * @Profile: 指定组件在哪个环境下才能被注册到容器中，不指定，任何情况下都能注册这个组件
 *  1.加了环境标识的bean，只有这个环境被激活的时候才能注册到容器中，默认是 default 环境
 *  2.写在配置类上，只有是指定的环境的时候，整个配置类里面的所有配置才能开始生效
 *  3.没有标注环境标识的 bean，任何环境下都是加载的
 * @author wuwenbo
 * @date 2020/4/8 - 23:38
 */
//@Profile("prod")
@PropertySource("classpath:/dbconfig.properties")//classpath 类路径下
@Configuration
public class MainConfigOfProfile  implements EmbeddedValueResolverAware {//实现 EmbeddedValueResolverAware 接口可以拿到值解析器

    @Value("${db.user}")
    private String user;
    private StringValueResolver stringValueResolver;
    String driverClass;
    @Bean
    public Yellow yellow(){
        return new Yellow();
    }

    @Profile("test")
    @Bean("testDataSource")
    public DataSource dataSourceTest(@Value("${db.password}") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://115.29.241.121:10000/test1");

        dataSource.setDriverClass(driverClass);
        return dataSource;
    }
    @Profile("dev")
    @Bean("devDataSource")
    public DataSource dataSourceDev(@Value("${db.password}") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://115.29.241.121:10000/ace");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }
    @Profile("prod")
    @Bean("prodDataSource")
    public DataSource dataSourceProd(@Value("${db.password}") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://115.29.241.121:10000/seckill");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        this.stringValueResolver = stringValueResolver;
        driverClass = stringValueResolver.resolveStringValue("${db.driverClass}");
    }
}
